<template>
    <el-dialog :title="form.id ? '编辑' : '新增'" v-model="visible"
      :close-on-click-modal="false" draggable>
      <el-form ref="dataFormRef" :model="form" :rules="dataRules" formDialogRef label-width="90px" v-loading="loading">
       <el-row :gutter="24">
    <el-col :span="12" class="mb20">
      <el-form-item label="所属辖区" prop="regionId">        
        <el-tree-select
								:data="regionTreeData"
								:props="{ value: 'id', label: 'name', children: 'children' }"
								check-strictly
								class="w100"
								clearable
								placeholder="请选择所属辖区"
                @node-click="regionNodeClickFun" 
								v-model="form.regionId"
							>
							</el-tree-select>
      </el-form-item>
      </el-col>

    <el-col :span="12" class="mb20">
      <el-form-item label="名称" prop="name">
        <el-input v-model="form.name" placeholder="请输入名称"/>
      </el-form-item>
      </el-col>

    <el-col :span="12" class="mb20">
      <el-form-item label="地址" prop="address">
        <el-input v-model="form.address" placeholder="请输入地址"/>
      </el-form-item>
      </el-col>

    <el-col :span="12" class="mb20">
      <el-form-item label="执法人员编号" prop="personNo">
        <el-input v-model="form.personNo" placeholder="请输入执法人员编号"/>
      </el-form-item>
      </el-col>

    <el-col :span="12" class="mb20">
      <el-form-item label="中心点" prop="lonLat">
        <el-input readonly v-model="form.lonLat" placeholder="请输入中心点"/>       
          <el-button type="primary" mapColumn="lonlat" mapColumnType="lonlat" :mapColumnValue="form.lonLat"  @click="getMapGeom($event)">选取</el-button>
          <el-button @click="clearGeom('lonlat')">清除</el-button>
      </el-form-item>
      </el-col>

    <el-col :span="12" class="mb20">
      <el-form-item label="类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择类型">
            <el-option :value="item.value*1" :label="item.label" v-for="(item, index) in substation_type" :key="index"></el-option>
          </el-select>
        </el-form-item>
      </el-col>

			</el-row>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="visible = false">取消</el-button>
          <el-button type="primary" @click="onSubmit" :disabled="loading">确认</el-button>
        </span>
      </template>
    </el-dialog>
    <mapLonlat @getMapLonlatEnd="getMapLonlatEndHandler" ref="mapLonlatRef"></mapLonlat>
</template>

<script setup lang="ts" name="SubstationDialog">
import { useDict } from '/@/hooks/dict';
import { useMessage } from "/@/hooks/message";
import { getObj, addObj, putObj } from '/@/api/environment/substation'
import { rule } from '/@/utils/validate';
import { regionTree } from '/@/api/admin/region';
const emit = defineEmits(['refresh']);
const mapLonlat = defineAsyncComponent(() => import('../../map/mapLonlat.vue'));
// 定义变量内容
const dataFormRef = ref();
const mapLonlatRef= ref();
const visible = ref(false)
const loading = ref(false)
const regionTreeData = ref<any[]>([]);
const mapToolsTitle=ref('');
const mapLonlatKey=ref();
const mapToolsOpen = ref(false);
const mapColumn= ref('');
const mapColumnType = ref('');
const mapColumnValue = ref('');
// 定义字典
const { substation_type } = useDict('substation_type')

// 提交表单数据
const form = reactive({
		id:'',
	  regionNo: '',
    regionId:'',
	  name: '',
	  address: '',
	  personNo: '',
	  lonLat: '',
	  type: '',
    geom:''
});

// 定义校验规则
const dataRules = ref({
        regionId: [{required: true, message: '所属辖区不能为空', trigger: 'blur'}],
        name: [{required: true, message: '名称不能为空', trigger: 'blur'}],
        address: [{required: true, message: '地址不能为空', trigger: 'blur'}],
        personNo: [{required: true, message: '执法人员编号不能为空', trigger: 'blur'}],
        lonLat: [{required: true, message: '中心点不能为空', trigger: 'blur'}],
        type: [{required: true, message: '类型不能为空', trigger: 'blur'}],
})

const regionNodeClickFun = (data, node, vm)=>{
  form.regionNo=data.regionCode;
  console.log('this _nodeClickFun', data.regionCode, node);
}

// 打开弹窗
const openDialog = (id: string) => {
  visible.value = true
  form.id = ''

  // 重置表单数据
	nextTick(() => {
		dataFormRef.value?.resetFields();
	});
  getRegionTreeData();
  // 获取substation信息
  if (id) {
    form.id = id
    getsubstationData(id)
  }
};

const getMapLonlatEndHandler=(value: string) => {
      let mapGeom=JSON.parse(value);
      if(mapGeom.center) form.lonLat= mapGeom.center;
      if(mapGeom.geom) form.geom= mapGeom.geom;
      console.log("从地图获取坐标值:" + mapGeom.center);
      
    }
    const  clearGeom=(column: string) => {
      if(column=='lonlat'){
        form.lonLat='';
      }else{
        form.geom='';
      }
    }
/**选取热区*/
const getMapGeom = (event: any) =>{
      mapToolsTitle.value = "选取地图热区";
      mapLonlatKey.value = new Date().getTime();
      mapToolsOpen.value = true;
      var el = event.currentTarget;
      // this.getTime=parseInt(new Date().getTime() / 1000) + '';
      mapColumn.value=el.attributes.mapColumn.value;
      mapColumnType.value=el.attributes.mapColumnType.value;
      mapColumnValue.value=el.attributes.mapColumnValue.value;
      mapLonlatRef.value.openDialog({
        mapColumn:el.attributes.mapColumn.value,
        mapColumnType:el.attributes.mapColumnType.value,
        mapColumnValue:el.attributes.mapColumnValue.value,
      });
    }
// 提交
const onSubmit = async () => {
	const valid = await dataFormRef.value.validate().catch(() => {});
	if (!valid) return false;

	try {
    loading.value = true;
		form.id ? await putObj(form) : await addObj(form);
		useMessage().success(form.id ? '修改成功' : '添加成功');
		visible.value = false;
		emit('refresh');
	} catch (err: any) {
		useMessage().error(err.msg);
	} finally {
    loading.value = false;
  }
};

// 初始化辖区数据
const getRegionTreeData = () => {
	// 获取辖区数据
	regionTree().then((res) => {
		regionTreeData.value = res.data;
	});
};

// 初始化表单数据
const getsubstationData = (id: string) => {
  // 获取数据
  loading.value = true
  getObj(id).then((res: any) => {
    Object.assign(form, res.data)
  }).finally(() => {
    loading.value = false
  })
};

// 暴露变量
defineExpose({
  openDialog
});
</script>